package com.acmen.easyapi.util;

import com.acmen.easyapi.model.Dictionary;
import com.acmen.easyapi.provider.DictionaryProvider;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author acmen
 * 字典工具类
 *
 */
public class DictionaryUtil {


    public static List<Dictionary> getDictsByType(String dictType) {
        DictionaryProvider dictionaryProvider = SpringContextUtil.getBean(DictionaryProvider.class);
        List<Dictionary> dicts = dictionaryProvider.selectList(dictType);
        List<Dictionary> dictionaries = dicts.stream()
                .map(d->new Dictionary(String.valueOf(d.getValue()),String.valueOf(d.getLabel())))
                .collect(Collectors.toList());
        return dictionaries;
    }

    /**
     *
     * @param enumClass
     * @return
     */
    public static List<Dictionary> getDictsFromEnum(Class enumClass) {
        Field[] fields = enumClass.getDeclaredFields();
        List<Dictionary> dictionaries = new ArrayList<>();
        for (Object enumObj : enumClass.getEnumConstants()) {
            Object value = EnumUtil.getEnumValue(enumObj,fields);
            Object desc = EnumUtil.getEnumDesc(enumObj,fields);
            Dictionary dict = new Dictionary(String.valueOf(value),String.valueOf(desc));
            dictionaries.add(dict);
        }
        return dictionaries;
    }

    public static List<Dictionary> getDictsFromEnum2(Class enumClass) {
        Field fields[] = enumClass.getDeclaredFields();
        List<Dictionary> dictionaries = new ArrayList<>();
        for (Object enumObj : enumClass.getEnumConstants()) {
            Object value = enumObj.toString();
            Object desc = EnumUtil.getEnumDesc(enumObj,fields);
            Dictionary dict = new Dictionary(String.valueOf(value),String.valueOf(desc));
            dictionaries.add(dict);
        }
        return dictionaries;
    }
}
